package com.csii.ams.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.csii.adhoc.id.UidGenerator;
import com.csii.adhoc.info.user.UserVo;
import com.csii.ams.ArchDef;
import com.csii.ams.mapper.ArchDefMapper;
import com.csii.ams.service.ArchDefService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: panChuanJiang
 * @create: 2021-03-18 09:25
 */
@Service("archDefService")
public class ArchDefServiceImpl implements ArchDefService {
    @Resource
    private ArchDefMapper archDefMapper;
    @Autowired
    private UidGenerator uidGenerator;


    @Override
    public void insertArchDef(ArchDef archDef) {
        archDef.setArchCd(uidGenerator.getUID()+"");
        archDefMapper.insertArchDef(archDef);
    }

    @Override
    public void updateArchDef(ArchDef archDef) {
        archDefMapper.updateArchDef(archDef);
    }

    @Override
    public List<ArchDef> queryListArchDef(ArchDef archDef) {
        return archDefMapper.queryListArchDef(archDef);
    }

    @Override
    public ArchDef queryOneArchDef(String archDef) {
        return archDefMapper.selectByPrimaryKey(archDef);
    }

    @Override
    public void deleteArchDef(String id) {
        archDefMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<ArchDef> queryArchDefs(Map<String,String> map, String filehome) {
        List<ArchDef> archDefs = archDefMapper.queryArchDefsAndAbn(map);
        for (ArchDef archDef : archDefs) {
            archDef.setExist(false);
            String archRule = archDef.getArchRule();
            JSONObject jsonObject;
            try {
                jsonObject = JSON.parseObject(archRule);
            }catch (Exception e){
                continue;
            }
            String role = String.valueOf(jsonObject.get("role"));
            if ("localFile".equals(role)) {
                String archCd = archDef.getArchCd();
                String path = filehome + File.separator + archCd + File.separator + map.get("idCard");
                File dir = new File(path);
                if (dir.exists() && dir.isDirectory()) {
                    File[] files = dir.listFiles();
                    for (File file : files) {
                        if (file.getName().contains(map.get("idCard"))){
                            archDef.setExist(true);
                            break;
                        }
                    }
                }
            }
        }
        return archDefs;
    }

}
